<template>
  <div class="outer-order-page">
    <el-button type="primary" @click="saveAll">保存修改</el-button>
    <el-button type="primary" @click="goBack">返回列表</el-button>
    
    <!-- 基本信息部分 -->
    <br/><br/>
    <el-card title="工艺详情">
      <el-form 
        :model="form" 
        label-width="120px" 
        ref="formRef" 
        :rules="rules"
      >
        <el-row>
          <el-col :span="10">
            <el-form-item label="工艺名称" prop="craftsmanshipName">
              <el-input v-model="form.craftsmanshipName" required></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="工艺编码" prop="craftsmanshipCode">
              <el-input placeholder="自动生成" disabled v-model="form.craftsmanshipCode"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="负责人" prop="leader">
              <el-input
                v-model="form.leader"
                :readonly="form.ourRepresentativesInfoFilled"
                required
              >
                <template #suffix>
                  <el-button size="mini" @click="openOurRepresentativesDialog">
                    <i class="el-icon-search"></i>
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属部门">
              <el-input v-model="form.affiliation" disabled></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="状态">
              <el-switch v-model="form.status"></el-switch>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="备注">
              <el-input type="textarea" v-model="form.remark"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </el-card>

    <!-- 已选工序列表区域 -->
    <el-card title="已选工序" style="margin-top: 20px; border-top: 3px solid #409eff;">
      <el-button @click="showProceduresDialog" style="margin-bottom: 10px;">选择工序</el-button>
      <div class="table-container">
        <el-table 
          :data="selectedProcedures" 
          stripe 
          height="200"
        >
          <el-table-column type="index" label="序号" width="80"></el-table-column>
          <el-table-column prop="processCode" label="工序编码" width="150"></el-table-column>
          <el-table-column prop="processName" label="工序名称"></el-table-column>
          <el-table-column prop="typeName" label="工序类型"></el-table-column>
          <el-table-column prop="leader" label="负责人"></el-table-column>
          <el-table-column prop="affiliation" label="所属部门" width="100"></el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag :type="scope.row.status === true ? 'success' : 'danger'">
                {{ scope.row.status === true ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="mini" type="danger" @click="removeProcedure(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 负责人选择对话框 -->
    <el-dialog
      v-model="ourRepresentativesDialogVisible"
      width="500px"
      title="我方代表选择"
      append-to-body
    >
      <el-table
        :data="ourRepresentativesList"
        highlight-current-row
        border
        size="small"
        @current-change="handleOurRepresentativesChange"
      >
        <el-table-column type="index" label="序号" />
        <el-table-column property="userName" label="代表姓名" />
        <el-table-column property="depmentName" label="部门" />
        <el-table-column property="roleName" label="职位" />
      </el-table>
      <template #footer>
        <el-button @click="ourRepresentativesDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="pickOurRepresentatives">确定</el-button>
      </template>
    </el-dialog>

    <!-- 工序选择对话框 -->
    <el-dialog
      v-model="proceduresDialogVisible"
      title="选择工序"
      width="80%"
      append-to-body
    >
      <el-input 
        v-model="procedureSearchKey" 
        placeholder="搜索工序名称/编码" 
        @keyup.enter.native="searchProcedures"
        style="width: 300px; margin: 15px 0;"
      >
        <template #suffix>
          <el-button slot="append" icon="el-icon-search" @click="searchProcedures">搜索</el-button>
        </template>
      </el-input>
      
      <el-table
        :data="availableProcedures"
        stripe
        border
        height="400"
        @selection-change="handleProceduresSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="processCode" label="工序编码" width="150"></el-table-column>
        <el-table-column prop="processName" label="工序名称"></el-table-column>
        <el-table-column prop="typeName" label="工序类型"></el-table-column>
        <el-table-column prop="leader" label="负责人"></el-table-column>
        <el-table-column prop="affiliation" label="所属部门" width="100"></el-table-column>
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === true ? 'success' : 'danger'">
              {{ scope.row.status === true ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      
      <el-pagination
        v-model:current-page="procedurePage.current"
        v-model:page-size="procedurePage.size"
        :page-sizes="[10, 20, 30, 50]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="procedureTotal"
        style="margin-top: 15px;"
        @size-change="handleProcedureSizeChange"
        @current-change="handleProcedureCurrentChange"
      />
      
      <template #footer>
        <el-button @click="proceduresDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelectedProcedures">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import axios from 'axios';
import { useRoute, useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();

// 表单验证规则
const rules = reactive({
  craftsmanshipName: [{ required: true, message: '请输入工艺名称', trigger: 'blur' }],
  leader: [{ required: true, message: '请选择负责人', trigger: 'blur' }]
});

// 基本信息表单数据
const form = ref({
  craftsmanshipId: null,
  craftsmanshipCode: "",
  craftsmanshipName: "",
  leader: "",
  affiliation: "",
  status: true,
  remark: "",
  ourRepresentativesInfoFilled: false
});

// 已选工序列表
const selectedProcedures = ref([]);

// 可选工序数据
const availableProcedures = ref([]);
const selectedProcedureRows = ref([]);
const procedurePage = ref({
  current: 1,
  size: 20
});
const procedureTotal = ref(0);
const procedureSearchKey = ref('');
const proceduresDialogVisible = ref(false);

// 我方代表列表
const ourRepresentativesList = ref([]);
const currentOurRepresentative = ref(null);
const ourRepresentativesDialogVisible = ref(false);

// 生命周期钩子
onMounted(() => {
  const craftsmanshipId = route.query.craftsmanshipId;
  if (!craftsmanshipId) {
    ElMessage.error('未获取到工艺ID');
    router.push({ name: 'GetCraftsmanshipView' });
    return;
  }
  
  form.value.craftsmanshipId = craftsmanshipId;
  
  // 并行加载数据
  Promise.all([
    fetchCraftsmanshipBaseInfo(),
    fetchCraftsmanshipProcedures(),
    fetchBaseData()
  ]).catch(error => {
    console.error('加载数据失败:', error);
    ElMessage.error('加载数据失败，请检查网络或联系管理员');
  });
});

// 获取基础数据（负责人列表）
const fetchBaseData = async () => {
  try {
    const { data } = await axios.get('http://8.154.44.176:8000/r-read/api/Depment/GetDepUserRole');
    ourRepresentativesList.value = data.data || [];
  } catch (error) {
    ElMessage.error('加载负责人列表失败');
    console.error('加载负责人列表失败:', error);
  }
};

// 获取工艺主表数据
const fetchCraftsmanshipBaseInfo = async () => {
  try {
    const { data } = await axios.get('http://8.154.44.176:8000/f-read/api/GetProcess/GetBYIdCraftsmanship', {
      params: {
        craftsmanshipId: form.value.craftsmanshipId
      }
    });
    
    if (data.code === 200 && data.data) {
      // 填充工艺基本信息
      form.value.craftsmanshipName = data.data[0].craftsmanshipName || '';
      form.value.craftsmanshipCode = data.data[0].craftsmanshipCode || '';
      form.value.leader = data.data[0].leader || '';
      form.value.affiliation = data.data[0].affiliation || '';
      form.value.status = data.data[0].status === undefined ? true : data.data[0].status;
      form.value.remark = data.data[0].remark || '';
      form.value.ourRepresentativesInfoFilled = !!data.data[0].leader;
      
      console.log('工艺主表数据加载成功', form.value);
    } else {
      ElMessage.error(`获取工艺基本信息失败：${data.message || '未找到数据'}`);
      console.error('获取工艺基本信息失败:', data.message);
    }
  } catch (error) {
    ElMessage.error('获取工艺基本信息失败，请检查网络或联系管理员');
    console.error('获取工艺基本信息失败:', error);
  }
};

// 获取工艺关联的工序数据
const fetchCraftsmanshipProcedures = async () => {
  try {
    const { data } = await axios.get('http://8.154.44.176:8000/f-read/api/GetProcess/GetBYIdCraftProcedure', {
      params: {
        craftsmanshipId: form.value.craftsmanshipId
      }
    });
    
    if (data.code === 200 && data.data) {
      // 填充已选工序
      selectedProcedures.value = data.data || [];
      console.log('工艺工序数据加载成功', selectedProcedures.value);
    } else {
      ElMessage.error(`获取工艺工序数据失败：${data.message || '未找到数据'}`);
      console.error('获取工艺工序数据失败:', data.message);
    }
  } catch (error) {
    ElMessage.error('获取工艺工序数据失败，请检查网络或联系管理员');
    console.error('获取工艺工序数据失败:', error);
  }
};

// 获取可选工序列表
const fetchAvailableProcedures = async () => {
  try {
    const { data } = await axios.get('http://8.154.44.176:8000/f-read/api/GetProcess/GetProcedure', {
      params: {
        PageIndex: procedurePage.value.current,
        PageSize: procedurePage.value.size,
        SearchKey: procedureSearchKey.value
      }
    });
    
    if (data.code === 200) {
      availableProcedures.value = data.data.list || [];
      procedureTotal.value = data.data.totalCount || 0;
      
      // 过滤掉已选的工序
      const selectedIds = selectedProcedures.value.map(p => p.procedureId);
      availableProcedures.value = availableProcedures.value.filter(p => !selectedIds.includes(p.procedureId));
      
      console.log('可选工序数据加载成功', availableProcedures.value);
    } else {
      ElMessage.error(`获取可选工序数据失败：${data.message}`);
      console.error('获取可选工序数据失败:', data.message);
    }
  } catch (error) {
    ElMessage.error('获取可选工序数据失败，请检查网络或联系管理员');
    console.error('获取可选工序数据失败:', error);
  }
};

// 打开负责人选择对话框
const openOurRepresentativesDialog = () => {
  if (ourRepresentativesList.value.length === 0) {
    ElMessage.warning('负责人数据加载中，请稍后重试');
    return;
  }
  ourRepresentativesDialogVisible.value = true;
};

// 处理负责人选择
const handleOurRepresentativesChange = (val) => {
  currentOurRepresentative.value = val;
};

// 确认选择负责人
const pickOurRepresentatives = () => {
  if (currentOurRepresentative.value) {
    form.value.leader = currentOurRepresentative.value.userName;
    form.value.affiliation = currentOurRepresentative.value.depmentName;
    form.value.ourRepresentativesInfoFilled = true;
    ourRepresentativesDialogVisible.value = false;
  } else {
    ElMessage.warning('请选择一个负责人');
  }
};

// 显示工序选择对话框
const showProceduresDialog = () => {
  procedurePage.value.current = 1;
  fetchAvailableProcedures();
  proceduresDialogVisible.value = true;
};

// 搜索工序
const searchProcedures = () => {
  procedurePage.value.current = 1;
  fetchAvailableProcedures();
};

// 处理工序选择变化
const handleProceduresSelectionChange = (val) => {
  selectedProcedureRows.value = val;
};

// 处理工序分页变化
const handleProcedureSizeChange = (size) => {
  procedurePage.value.size = size;
  fetchAvailableProcedures();
};

// 处理工序页码变化
const handleProcedureCurrentChange = (current) => {
  procedurePage.value.current = current;
  fetchAvailableProcedures();
};

// 确认选择工序
const confirmSelectedProcedures = () => {
  if (selectedProcedureRows.value.length === 0) {
    ElMessage.warning('请选择工序');
    return;
  }
  
  // 添加到已选列表
  selectedProcedures.value = [...selectedProcedures.value, ...selectedProcedureRows.value];
  
  // 关闭对话框
  proceduresDialogVisible.value = false;
  
  ElMessage.success(`成功添加 ${selectedProcedureRows.value.length} 个工序`);
};

// 删除已选工序
const removeProcedure = (procedure) => {
  selectedProcedures.value = selectedProcedures.value.filter(p => p.procedureId !== procedure.procedureId);
  ElMessage.success('已删除所选工序');
};

  // 表单ref
  const formRef = ref(null);

// 保存工艺修改
const saveAll = async () => {
  if (!formRef.value) return;
  
  try {
    await formRef.value.validate();
    
    if (selectedProcedures.value.length === 0) {
      ElMessage.warning('请至少选择一个工序');
      return;
    }
    
    const loading = ElLoading.service({
      lock: true,
      text: '保存中...',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    try {
      // 保存主表单
      const { data } = await axios.post(
        'http://8.154.44.176:8000/f-write/api/Process/UpdateCraftsmanship',
        form.value
      );

      if (data.code === 200) {
        // 保存成功，保存工艺工序关系
        const craftsmanshipId = data.data?.craftsmanshipId || form.value.craftsmanshipId;
        
        // 先删除原有关联关系（更新为新接口，将数组转为字符串）
        await deleteCraftProcedures([craftsmanshipId]);
        
        // 再添加新的关联关系
        await saveCraftProceduresRelation(craftsmanshipId);
        
        ElMessage.success('工艺修改成功');
        setTimeout(() => {
          router.push({ name: 'GetCraftsmanshipView' });
        }, 1500);
      } else {
        ElMessage.error(`保存失败：${data.message}`);
      }
    } finally {
      loading.close();
    }
  } catch (error) {
    ElMessage.error('保存过程中发生错误，请检查网络或联系管理员');
    console.error('保存失败:', error);
  }
};

// 删除工艺工序关联关系（更新为新接口，将数组转为字符串）
const deleteCraftProcedures = async (craftsmanshipIds) => {
  try {
    // 将数组转换为字符串（例如：[1,2,3] 转为 "1,2,3"）
    const craftsmanshipIdsStr = craftsmanshipIds.join(',');
    
    const { data } = await axios.post(
      'http://8.154.44.176:8000/f-write/api/Process/DelCraftProcedure',
      { craftsmanshipIds: craftsmanshipIdsStr } // 传递字符串类型的ID列表
    );
    
    if (data.code !== 200) {
      console.error('删除工艺工序关系失败:', data.message);
    }
  } catch (error) {
    console.error('删除工艺工序关系失败:', error);
  }
};

// 保存工艺工序关联关系（批量）
const saveCraftProceduresRelation = async (craftsmanshipId) => {
  try {
    for (const procedure of selectedProcedures.value) {
      const relation = {
        craftsmanshipId: craftsmanshipId,
        procedureId: procedure.procedureId
      };
      const { data } = await axios.post(
        'http://8.154.44.176:8000/f-write/api/Process/AddCraftProcedure',
        relation
      );
      if (data.code!== 200) {
        ElMessage.error(`保存工序关系失败：${data.message}`);
        console.error('保存工序关系失败:', data.message);
        return;
      }
    }
    console.log('工艺工序关系保存成功');
  } catch (error) {
    ElMessage.error('保存工序关系失败，请检查网络或联系管理员');
    console.error('保存工序关系失败:', error);
  }
};
// 返回列表页
const goBack = () => {
  router.push({ name: 'GetCraftsmanshipView' });
};
</script>

<style scoped>
.table-container {
  margin-top: 20px;
}

.el-button + .el-button {
  margin-left: 10px;
}
</style>  